<?php

class Advmenusystem_IndexController extends Core_Controller_Action_Standard
{
    public function totalAction() {
        $viewer = Engine_Api::_()->user()->getViewer();
        if (!$viewer->getIdentity()) {
            $this->_helper->viewRenderer->setNoRender(true);
        }
        $notificationTb = Engine_Api::_()->getDbtable('notifications', 'activity');
        $tbName = $notificationTb->info('name');
        $db = $notificationTb->getAdapter();
        $db->beginTransaction();
        try {
            $notif = $db->query("SELECT COUNT(*) AS total FROM $tbName WHERE `user_id` = {$viewer->getIdentity()} AND `read` = 0 AND `type` <> 'friend_request' AND `type` <> 'message_new'")->fetch();
            $freq = $db->query("SELECT COUNT(*) AS total FROM $tbName WHERE `user_id` = {$viewer->getIdentity()} AND `read` = 0 AND `type` = 'friend_request'")->fetch();
        } catch (Exception $ex) {
            $db->rollBack();
            echo $ex->getMessage();
            return;
        }

        $data = array(
            'notification' => $notif['total'],
            'freq' => $freq['total'],
            'msg' => Engine_Api::_()->messages()->getUnreadMessageCount($viewer)   
        );
        return $this->_helper->json($data);
    }
    public function cancelFriendAction() {
        // Get Viewer
        $viewer = Engine_Api::_()->user()->getViewer();
        if (!$viewer->getIdentity()) {
            // Set Norender if user is not logged on
            return false;
        }
        $resource_id = $this->getRequest()->getParam('resource_id');
        $user = Engine_Api::_()->getItem('user', $resource_id);  
        $this->view->status = false;
        $this->view->resource_id = $resource_id;
        if ($resource_id) {
            $uid    = $viewer->getIdentity();
            $userTb = Engine_Api::_()->getDbTable('membership', 'user');
            $db = $userTb->getAdapter();
            $db->beginTransaction();
            $select = $userTb->select()
                            ->where("(user_id = $uid AND resource_id = $resource_id)
                                    OR (user_id = $resource_id AND resource_id = $uid)")
                            ->where("active = 0");
            $rows = $userTb->fetchAll($select);
            try {
                if (count($rows)) {
                    foreach ($rows as $row) {
                        $row->delete();
                    }
                    // Set the requests as handled
                      $notification = Engine_Api::_()->getDbtable('notifications', 'activity')
                          ->getNotificationBySubjectAndType($viewer, $user, 'friend_request');
                      if( $notification ) {
                        $notification->mitigated = true;
                        $notification->read = 1;
                        $notification->save();
                      }
                      $notification = Engine_Api::_()->getDbtable('notifications', 'activity')
                          ->getNotificationBySubjectAndType($viewer, $user, 'friend_follow_request');
                      if( $notification ) {
                        $notification->mitigated = true;
                        $notification->read = 1;
                        $notification->save();
                      }
                    $db->commit();
                    $this->view->status = true;
                }
            } catch (Exception $e) {
                $db->rollBack();
                throw $e;
            }
        }
    }
    public function confirmFriendAction() {
        // Get Viewer
        $viewer = Engine_Api::_()->user()->getViewer();
        if (!$viewer->getIdentity()) {
            // Set Norender if user is not logged on
            return false;
        }
        $resource_id = $this->getRequest()->getParam('resource_id');
        $this->view->status = false;
        $this->view->resource_id = $resource_id;
        $user = Engine_Api::_()->getItem('user', $resource_id);
        if ($resource_id) {
            $uid    = $viewer->getIdentity();
            $userTb = Engine_Api::_()->getDbTable('membership', 'user');
            $db = $userTb->getAdapter();
            $db->beginTransaction();
            $select = $userTb->select()
                            ->where("(user_id = $uid AND resource_id = $resource_id)
                                    OR (user_id = $resource_id AND resource_id = $uid)")
                            ->where("active = 0");
            $rows = $userTb->fetchAll($select);
            try {
                if (count($rows)) {
                    foreach ($rows as $row) {
                        $row->active = 1;
                        $row->user_approved = 1;
                        $row->resource_approved = 1;
                        $row->save();
                    }
                     // Add activity
                      if( !$user->membership()->isReciprocal() ) {
                        Engine_Api::_()->getDbtable('actions', 'activity')
                            ->addActivity($user, $viewer, 'friends_follow', '{item:$subject} is now following {item:$object}.');
                      } else {
                        Engine_Api::_()->getDbtable('actions', 'activity')
                          ->addActivity($user, $viewer, 'friends', '{item:$object} is now friends with {item:$subject}.');
                        Engine_Api::_()->getDbtable('actions', 'activity')
                          ->addActivity($viewer, $user, 'friends', '{item:$object} is now friends with {item:$subject}.');
                      }
                      
                      // Add notification
                      if( !$user->membership()->isReciprocal() ) {
                        Engine_Api::_()->getDbtable('notifications', 'activity')
                          ->addNotification($user, $viewer, $user, 'friend_follow_accepted');
                      } else {
                        Engine_Api::_()->getDbtable('notifications', 'activity')
                          ->addNotification($user, $viewer, $user, 'friend_accepted');
                      }
                    // Set the requests as handled
                      $notification = Engine_Api::_()->getDbtable('notifications', 'activity')
                          ->getNotificationBySubjectAndType($viewer, $user, 'friend_request');
                      if( $notification ) {
                        $notification->mitigated = true;
                        $notification->read = 1;
                        $notification->save();
                      }
                      $notification = Engine_Api::_()->getDbtable('notifications', 'activity')
                          ->getNotificationBySubjectAndType($viewer, $user, 'friend_follow_request');
                      if( $notification ) {
                        $notification->mitigated = true;
                        $notification->read = 1;
                        $notification->save();
                      }
                    $db->commit();
                    $this->view->status = true;
                }
            } catch (Exception $e) {
                $db->rollBack();
                throw $e;
            }
        }   
    }
    /**
     * Message alert
     * @todo get message
     * @access public
     */
    public function messageAction() {
        // Get Viewer
        $viewer = Engine_Api::_()->user()->getViewer();
        if (!$viewer->getIdentity()) {
            // Set Norender if user is not logged on
            return false;
        }
        // Get Parameters
        $do = $this->getRequest()->getParam('do');
        $nid = $this->getRequest()->getParam('nid');
        $nids = json_decode($this->getRequest()->getParam('nids'));
        if ($do == 'markread') {
            // If mark read action   
            if ($nids && is_array($nids)) {
                $notificationsTable = Engine_Api::_()->getDbtable('notifications', 'activity');
                $db = $notificationsTable->getAdapter();
                $db->beginTransaction();
                try {
                    // Get notification
                    $notifications = $notificationsTable->fetchAll("`user_id` = {$viewer->getIdentity()} AND `type` = 'message_new' AND `read` = 0 AND `notification_id` IN (" . implode(', ', $nids) . ")");
                    if ($notifications) {
                        foreach ($notifications as $notification) {
                            $notification->read = 1; // set it as read
                            $notification->mitigated = 1;
                            $notification->save();
                        }
                        $db->commit();
                    }
                } catch (Exception $e) {
                    $db->rollBack();
                    throw $e;
                }
            } else if ($nid) {
                // If notification is set
                $notificationsTable = Engine_Api::_()->getDbtable('notifications', 'activity');
                $db = $notificationsTable->getAdapter();
                $db->beginTransaction();
                try {
                    // Get notification
                    $notification = $notificationsTable->fetchRow("`user_id` = {$viewer->getIdentity()} AND `type` = 'message_new' AND `read` = 0 AND `notification_id` = $nid");
                    if ($notification) {
                        $notification->read = 1; // set it as read
                        $notification->mitigated = 1;
                        $notification->save();
                        $db->commit();
                    }
                } catch (Exception $e) {
                    $db->rollBack();
                    throw $e;
                }
            }

            return false;
        }
        // Get Message notifications 
        $total = Engine_Api::_()->messages()->getUnreadMessageCount($viewer);
        $this->view->total = $total; 
        // Get Message
        $limit = $total < 5 ? $total : 5;
        $table = Engine_Api::_()->getItemTable('messages_conversation');
        $rName = Engine_Api::_()->getDbtable('recipients', 'messages')->info('name');
        $cName = $table->info('name');
        $select = $table->select()
          ->from($cName)
          ->joinRight($rName, "`{$rName}`.`conversation_id` = `{$cName}`.`conversation_id`", null)
          ->where("`{$rName}`.`user_id` = ?", $viewer->getIdentity())
          ->where("`{$rName}`.`inbox_deleted` = ?", 0)
          ->order('inbox_read ASC')
          ->order(new Zend_Db_Expr('inbox_updated DESC'))
          ->limit(5);
        $this->view->msg = $msg = $table->fetchAll($select); 
    
        $this->_helper->layout->disableLayout();
    }
    public function notificationsAction() {
        $viewer = Engine_Api::_()->user()->getViewer();
         $select = Engine_Api::_()->getDbTable('notifications', 'activity')
                        ->select()
                        ->where("`user_id` = ?", $viewer->getIdentity())
                        ->where("`type` <> 'friend_request'")
                        ->where("`type` <> 'message_new'")
                        ->order('read ASC')
                        ->order('notification_id DESC');
        $this->view->notifications = $notifications = Zend_Paginator::factory($select);
        $notifications->setCurrentPageNumber($this->_getParam('page'));

        // Force rendering now
        $this->_helper->viewRenderer->postDispatch();
        $this->_helper->viewRenderer->setNoRender(true);

        $this->view->hasunread = false;

        // Now mark them all as read
        $ids = array();
        foreach( $notifications as $notification ) {
          $ids[] = $notification->notification_id;
        }
    }
    public function markreadAction()
    {
    $request = Zend_Controller_Front::getInstance()->getRequest();
    $action_id = $request->getParam('actionid', 0);
    $viewer = Engine_Api::_()->user()->getViewer();
    $notificationsTable = Engine_Api::_()->getDbtable('notifications', 'activity');
    $db = $notificationsTable->getAdapter();
    $db->beginTransaction();

    try {
      $notification = Engine_Api::_()->getItem('activity_notification', $action_id);
      $notification->read = 1;
      $notification->save();
      // Commit
      $db->commit();
    } catch( Exception $e ) {
      $db->rollBack();
      throw $e;
    }
  } 
     public function pulldownAction()
  {
    $page = $this->_getParam('page');
    $viewer = Engine_Api::_()->user()->getViewer();
    $select = Engine_Api::_()->getDbTable('notifications', 'activity')
                        ->select()
                        ->where("`user_id` = ?", $viewer->getIdentity())
                        ->where("`type` <> 'friend_request'")
                        ->where("`type` <> 'message_new'")
                        ->order('notification_id DESC');
    $this->view->notifications = $notifications = Zend_Paginator::factory($select);
    $notifications->setCurrentPageNumber($page);

    if( $notifications->getCurrentItemCount() <= 0 || $page > $notifications->getCurrentPageNumber() ) {
      $this->_helper->viewRenderer->setNoRender(true);
      return;
    }

    // Force rendering now
    $this->_helper->viewRenderer->postDispatch();
    $this->_helper->viewRenderer->setNoRender(true);
  }
    /**
     * Notification alert
     * @todo get notification
     * @access public
     */
     public function notificationAction() {
        // Get Viewer
        $viewer = Engine_Api::_()->user()->getViewer();
        if (!$viewer->getIdentity()) {
            // Set Norender if user is not logged on
            return false;
        }
        // Get Parameters
        $do = $this->getRequest()->getParam('do');
        $nid = $this->getRequest()->getParam('nid');
        $nids = json_decode($this->getRequest()->getParam('nids'));
        if ($do == 'markread') {
            // If mark read action  
            if ($nids && is_array($nids)) {
                $notificationsTable = Engine_Api::_()->getDbtable('notifications', 'activity');
                $db = $notificationsTable->getAdapter();
                $db->beginTransaction();
                try {
                    // Get notification
                    $notifications = $notificationsTable->fetchAll("`user_id` = {$viewer->getIdentity()} AND `type` <> 'friend_request' AND `type` <> 'message_new' AND `read` = 0 AND `notification_id` IN (" . implode(', ', $nids) . ")");
                    if ($notifications) {
                        foreach ($notifications as $notification) {
                            $notification->read = 1; // set it as read
                            $notification->mitigated = 1;
                            $notification->save();
                        }
                        $db->commit();
                    }
                } catch (Exception $e) {
                    $db->rollBack();
                    throw $e;
                }
            } else if ($nid) {
                // If notification is set
                $notificationsTable = Engine_Api::_()->getDbtable('notifications', 'activity');
                $db = $notificationsTable->getAdapter();
                $db->beginTransaction();
                try {
                    // Get notification
                    $notification = $notificationsTable->fetchRow("`user_id` = {$viewer->getIdentity()} AND `read` = 0 AND `type` <> 'friend_request' AND `notification_id` = $nid");
                    if ($notification) {
                        $notification->read = 1; // set it as read
                        $notification->mitigated = 1;
                        $notification->save();
                        $db->commit();
                    }
                } catch (Exception $e) {
                    $db->rollBack();
                    throw $e;
                }
            }
            return false;
        }
        // Get notifications

        $this->view->nmsg = $nmsg = Engine_Api::_()->getDbTable('notifications', 'activity')->fetchAll("`user_id` = {$viewer->getIdentity()} AND `read` = 0 AND `type` <> 'friend_request' AND `type` <> 'message_new'");

        //$total = count($nmsg);
        //$limit = $total < 5 ? $total : 5;
        $select = Engine_Api::_()->getDbTable('notifications', 'activity')
                        ->select()
                        ->where("`user_id` = ?", $viewer->getIdentity())
                        ->where("`type` <> 'friend_request'")
                        ->where("`type` <> 'message_new'")
                        ->order('read ASC')
                        ->order('notification_id DESC')
                        ->limit(5);
        $this->view->msg = Engine_Api::_()->getDbTable('notifications', 'activity')->fetchAll($select);
        $this->_helper->layout->disableLayout();
    }
    /**
     * Friend request alert
     * @todo get friend request
     * @access public
     */
     public function friendAction() {
        $viewer = Engine_Api::_()->user()->getViewer();
        if (!$viewer->getIdentity()) {
            return false;
        }
        $do = $this->getRequest()->getParam('do');
        $nid = $this->getRequest()->getParam('nid');
        $nids = json_decode($this->getRequest()->getParam('nids'));
        if ($do == 'markread') {
            // If mark read action
            if ($nids && is_array($nids)) {
                $notificationsTable = Engine_Api::_()->getDbtable('notifications', 'activity');
                $db = $notificationsTable->getAdapter();
                $db->beginTransaction();
                try {
                    // Get notification
                    $notifications = $notificationsTable->fetchAll("`user_id` = {$viewer->getIdentity()} AND `type` = 'friend_request' AND `read` = 0 AND `notification_id` IN (" . implode(', ', $nids) . ")");
                    if ($notifications) {
                        foreach ($notifications as $notification) {
                            $notification->read = 1; // set it as read
                            //$notification->mitigated = 1;
                            $notification->save();
                        }
                        $db->commit();
                    }
                } catch (Exception $e) {
                    $db->rollBack();
                    throw $e;
                }
            } else if ($nid) {
                // If notification is set
                $notificationsTable = Engine_Api::_()->getDbtable('notifications', 'activity');
                $db = $notificationsTable->getAdapter();
                $db->beginTransaction();
                try {
                    // Get notification
                    $notification = $notificationsTable->fetchRow("`user_id` = {$viewer->getIdentity()} AND `type` = 'friend_request' AND `read` = 0 AND `notification_id` = $nid");
                    if ($notification) {
                        $notification->read = 1; // set it as read
                        //$notification->mitigated = 1;
                        $notification->save();
                        $db->commit();
                    }
                } catch (Exception $e) {
                    $db->rollBack();
                    throw $e;
                }
            }
            return false;
        }
        $this->view->ntype = Engine_Api::_()->getDbTable('notificationTypes', 'activity')->getNotificationType('friend_request');
        $select = Engine_Api::_()->getDbTable('notifications', 'activity')
                        ->select()
                        ->where("`user_id` = ? AND `type` = 'friend_request' AND `read` = 0", $viewer->getIdentity())
                        ->order('notification_id DESC');
        $this->view->nmsg = Engine_Api::_()->getDbTable('notifications', 'activity')->fetchAll($select);

        // Get Friend request but not confirm yet
        $userTb = Engine_Api::_()->getDbTable('membership', 'user');
        $select = $userTb->select()
                        ->where("user_id = ?", $viewer->getIdentity())
                        ->where("active = 0 AND resource_approved = 1 AND user_approved = 0");
        $this->view->freqs = $userTb->fetchAll($select);
        $this->_helper->layout->disableLayout();
    }
    public function markallreadAction()
    {
        $viewer = Engine_Api::_()->user()->getViewer();
        if (!$viewer->getIdentity()) {
            // Set Norender if user is not logged on
            return false;
        }
        $notificationsTable = Engine_Api::_()->getDbtable('notifications', 'activity');
            $db = $notificationsTable->getAdapter();
            $db->beginTransaction();
            try {
                // Get notification
                $notifications = $notificationsTable->fetchAll("`user_id` = {$viewer->getIdentity()} AND `type` <> 'friend_request' AND `type` <> 'message_new' AND `read` = 0");
                if ($notifications) {
                    foreach ($notifications as $notification) {
                        $notification->read = 1; // set it as read
                        $notification->mitigated = 1;
                        $notification->save();
                    }
                    $db->commit();
                }
            } catch (Exception $e) {
                $db->rollBack();
                throw $e;
            }
    }
     public function friendRequestsAction() {
        $viewer = Engine_Api::_()->user()->getViewer();
        if (!$viewer->getIdentity()) {
            return false;
        }
        $select = Engine_Api::_()->getDbTable('notifications', 'activity')
                        ->select()->from("engine4_activity_notifications")
                        ->where("engine4_activity_notifications.user_id = ? AND `type` = 'friend_request'", $viewer->getIdentity())
                        ->where('mitigated = ?', 0)
                        ->order('notification_id DESC');
        $this->view->requests = $requests = Zend_Paginator::factory($select); 
        $requests->setCurrentPageNumber($this->_getParam('page'));
    }
}
if ( !function_exists('json_decode') ){
    function json_decode($json)
    {
        $comment = false;
        $out = '$x=';
     
        for ($i=0; $i<strlen($json); $i++)
        {
            if (!$comment)
            {
                if (($json[$i] == '{') || ($json[$i] == '['))       $out .= ' array(';
                else if (($json[$i] == '}') || ($json[$i] == ']'))   $out .= ')';
                else if ($json[$i] == ':')    $out .= '=>';
                else                         $out .= $json[$i];         
            }
            else $out .= $json[$i];
            if ($json[$i] == '"' && $json[($i-1)]!="\\")    $comment = !$comment;
        }
        eval($out . ';');
        return $x;
    }
}